package com.cynteka.cyfoman.core;

import com.cynteka.cyfoman.core.config.ValueObjectListener;

import java.util.*;

/**
 * User: Sergey
 * Date: 29.07.11
 * Time: 17:37
 */
public class ValueObject<ID, P> extends HashMap<P, Object> implements IValueObject<ID, P> {
    private List<ValueObjectListener> listeners = new ArrayList<ValueObjectListener>();

    private ID id;
//     private final Map<P, Object> params = this; // new HashMap<P, Object>();

    public void setId(ID id) {
        this.id = id;
    }

    @Override
    public ID getId() {
        return id;
    }

    public Set<P> getParams() {
        return keySet();
    }

    @Override
    public void setParam(P paramName, Object value) {
        put(paramName, value);
    }

    @Override
    public Object getParam(P paramName) {
        return get(paramName);
    }

    @Override
    public String toString() {
        return "ValueObject{" +
                "id=" + id +
                ", params=" + super.toString() +
                '}';
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;

        ValueObject that = (ValueObject) o;

        if (id != null ? !id.equals(that.id) : that.id != null) return false;

        return true;
    }

    @Override
    public int hashCode() {
        return id != null ? id.hashCode() : 0;
    }
    public void addListener(ValueObjectListener listener) {
        listeners.add(listener);
    }

    public void removeListener(ValueObjectListener listener) {
        listeners.remove(listener);
    }

    public void fireChanged() {
        for (ValueObjectListener listener : listeners) {
            listener.changed(this);
        }
    }

    public void firePrepareToBeStored() {
        for (ValueObjectListener listener : listeners) {
            listener.prepareToBeStored(this);
        }
    }

    public Map getMap() {
        return Collections.unmodifiableMap(this);
    }

    @Override
    public Object put(P key, Object value) {
        return super.put(key, value);    //To change body of overridden methods use File | Settings | File Templates.
    }
}
